#include "hfloatingmessage.h"

#include <QGridLayout>
#include <QFontMetrics>
#include <QApplication>
#include <QScreen>
#include <QDesktopWidget>
#include <QIcon>
#include <QDebug>

HFloatingMessage::HFloatingMessage(QWidget *parent) : QDialog(parent)
{
    setWindowFlags(this->windowFlags()|Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
    setBackgroundRole(QPalette::Background);

    connect(&mTimer, SIGNAL(timeout()), this, SLOT(onTimer()));
    mTimer.setInterval(5000);

    QHBoxLayout* mainlayout = new QHBoxLayout(this);
    mainlayout->setContentsMargins(0, 0, 0, 0);

    mIconLabel = new QLabel(this);
    mTextLabel = new QLabel(this);
    mTextLabel->setAlignment(Qt::AlignCenter);
    mainlayout->addWidget(mIconLabel);
    mainlayout->addWidget(mTextLabel);

    mIconLabel->setMaximumWidth(30);
    mTextLabel->setWordWrap(true);
    mTextLabel->setContentsMargins(0, 0, 0, 0);
}

void HFloatingMessage::setText(const QString &text)
{
    mText = text;
    mTextLabel->setText(mText);
}

void HFloatingMessage::setDuration(int msec)
{
    mTimer.setInterval(msec);
}

void HFloatingMessage::setIcon(const QIcon &icon)
{
    mIconLabel->setPixmap(icon.pixmap(60, 60));
}

void HFloatingMessage::showEvent(QShowEvent *e)
{
    QFontMetrics fm = this->fontMetrics();
    QRect rc = fm.boundingRect(mText);
    if (mText.isEmpty()) {
        rc.setRect(0, 0, 200, 30);
    }
    int maxw = 500;
    if (parentWidget()) {
        maxw = parentWidget()->width();
    }
    int hs = rc.width() / maxw + 1;
    if (hs > 1)
        rc.setWidth(maxw);
    if (rc.height() < 50) {
        rc.setHeight(50);
    }
    rc.setHeight(hs*rc.height());
    setFixedSize(rc.width(), rc.height());

    int x, y;
    if (parentWidget()){
        QPoint p = parentWidget()->rect().center();
        x = p.x() - rc.width()/2;
        y = p.y() + (parentWidget()->height() - rc.height())/2 - 10;
    } else {
        QDesktopWidget d;
        QRect sc = d.screenGeometry(d.primaryScreen());
        x = (sc.width() - rc.width())/2;
        y = (sc.height() - rc.height()) - 20;
    }
    move(x, y);
    mTimer.start();
    QDialog::showEvent(e);
}

void HFloatingMessage::onTimer()
{
    this->accept();
}
